package Mycode.SlidingWindow.Leetcode.Leetcode395;

import java.util.Arrays;

public class L395 {
    class Solution {
        public int longestSubstring(String str, int k) {
            char[] s = str.toCharArray();
            int[] cnts = new int[256];
            int n = s.length;
            int ans = 0;
            //collect 当前窗口收集到的字符种类数
            //satisfy 当前窗口满足条件的种类的数量
            for (int require = 1; require <= 26; require++) {
                Arrays.fill(cnts, 0);
                for (int r = 0, l = 0, collect = 0, satisfy = 0; r < n; r++) {
                    cnts[s[r]]++;
                    if (cnts[s[r]] == 1) {
                        collect++;
                    }
                    if (cnts[s[r]] == k) {
                        satisfy++;
                    }
                    //处理种数超过require的情况

                    while (collect > require) {
                        if (cnts[s[l]] == k) {
                            satisfy--;
                        }
                        if (cnts[s[l]] == 1) {
                            collect--;
                        }
                        cnts[s[l++]]--;

                    }
                    //合规，更新答案
                    if (collect == satisfy) {
                        ans = Math.max(ans, r - l + 1);
                    }
                }

            }
            return ans;
        }
    }
}




